package v1

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"

	"application/model"
	"application/pkg/app"
)

type AddHouseBody struct {
	UserId   int     `json:"uid" form:"uid"`
	Area     int     `json:"area" form:"area"`
	RealArea int     `json:"real_area" form:"real_area"`
	Price    float64 `json:"price" form:"price"`
}

type DelHouseBody struct {
	HouseId int `json:"hid" form:"hid"`
}

type HouseListBody struct {
	UserId int    `json:"uid" form:"uid"`
	Page   int    `json:"page" form:"page"`
	Size   int    `json:"size" form:"size"`
	Search string `json:"search" form:"search"`
}

type List struct {
	Houses []model.House `json:"list" form:"list"`
	Page   int           `json:"page"  form:"page"`
}

// AddHouse 添加房屋信息
func AddHouse(c *gin.Context) {
	appG := app.Gin{C: c}
	body := new(AddHouseBody)
	//解析Body参数
	if err := c.ShouldBind(body); err != nil {
		appG.Response(http.StatusBadRequest, "失败", fmt.Sprintf("参数出错%s", err.Error()))
		return
	}
	res := model.AddHouse(model.House{
		UserId:     body.UserId,
		Area:       body.Area,
		RealArea:   body.RealArea,
		Price:      body.Price,
		Status:     0,
		IsRegister: 0,
	})
	appG.Response(http.StatusOK, "添加房屋信息成功", fmt.Sprintf("%d", res))
	return
}

// DelHouse 删除房源信息
func DelHouse(c *gin.Context) {
	appG := app.Gin{C: c}
	body := new(DelHouseBody)
	if err := c.ShouldBind(body); err != nil {
		appG.Response(http.StatusBadRequest, "失败", fmt.Sprintf("参数出错%s", err.Error()))
		return
	}
	err := model.DeleteHouse(body.HouseId)
	if err != nil {
		appG.Response(http.StatusBadRequest, "失败", fmt.Sprintf("数据库出错%s", err.Error()))
		return
	}
	appG.Response(http.StatusOK, "删除房屋信息成功", nil)
	return
}

// 房屋列表接口
func HouseList(c *gin.Context) {
	appG := app.Gin{C: c}
	body := new(HouseListBody)
	if err := c.ShouldBind(body); err != nil {
		appG.Response(http.StatusBadRequest, "失败", fmt.Sprintf("参数出错%s", err.Error()))
		return
	}
	list, page := model.SelectHouse(body.UserId, body.Page, body.Size, body.Search)
	houses := List{
		Houses: list,
		Page:   page,
	}
	appG.Response(http.StatusOK, "获取房屋列表成功", houses)
	return
}

// 修改房屋信息接口
func UpHouse(c *gin.Context) {
	appG := app.Gin{C: c}
	body := new(AddHouseBody)
	//解析Body参数
	if err := c.ShouldBind(body); err != nil {
		appG.Response(http.StatusBadRequest, "失败", fmt.Sprintf("参数出错%s", err.Error()))
		return
	}
	err := model.Update(model.House{
		UserId:     body.UserId,
		Area:       body.Area,
		RealArea:   body.RealArea,
		Price:      body.Price,
		Status:     0,
		IsRegister: 0,
	})
	if err != nil {
		appG.Response(http.StatusBadRequest, "失败", fmt.Sprintf("数据库出错%s", err.Error()))
		return
	}
	appG.Response(http.StatusOK, "修改房屋信息成功", nil)
	return
}
